//
//  MineMyAddressController.m
//  Experss
//
//  Created by 嗯，大葱 on 17/8/8.
//  Copyright © 2017年 嗯，大葱. All rights reserved.
//

#import "MineMyAddressController.h"

#import "MyAddressTableViewCell.h"

#import "AddAddressInfoController.h"//添加地址

#import "AddressListModel.h"

#import "CancelDingDanView.h"//

static NSString *identifier = @"MyAddressTableViewCell";

@interface MineMyAddressController ()<UITableViewDataSource,UITableViewDelegate,CancelDingDanViewDelegate>
{
    NSIndexPath *deleteIndex;
}
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong)UIButton *rightBtn2;//右侧按钮

@property (nonatomic, strong)NSMutableArray *dataArray;
//无地址时加载图
@property (nonatomic, strong)UIImageView *imageV;
@property (nonatomic, strong)UILabel *twoLabel;
@property (nonatomic, strong)UIButton *daiNiFeiBtn;

@end

@implementation MineMyAddressController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"我的地址";
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
    [self addTableviewUI];
    _dataArray = [NSMutableArray array];
    //    [self getData];
    // Do any additional setup after loading the view from its nib.
    [self configureNaBar];
    
    
}


//获取数据
- (void)getData {
    //取本地的userid
    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    NSDictionary *dic = @{@"userid":saveDic[@"userid"],@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest getWithURLString:POST(GetAllAddress) parameters:dic success:^(id responseObject) {
        NSLog(@"-=--=-=%@",responseObject);
        if ([responseObject[@"ret"] intValue] != 200) {
            [MBProgressHUD showText:@"网络错误"];
            return ;
        }
        NSArray *tempA = responseObject[@"data"][@"info"];
        
        if (self.dataArray.count) {
            [self.dataArray removeAllObjects];
        }
        for (NSDictionary *tempD in tempA) {
            AddressListModel *model = [[AddressListModel alloc] init];
            [model setValuesForKeysWithDictionary:tempD];
            [self.dataArray addObject:model];
            
        }
        
        [self.tableView reloadData];
        
        if (self.dataArray.count == 0) {
            self.tableView.hidden = YES;
            if (_imageV) {
                [_imageV removeFromSuperview];
            }
            
            if (_twoLabel) {
                [_twoLabel removeFromSuperview];
            }
            if (_daiNiFeiBtn) {
                [_daiNiFeiBtn removeFromSuperview];
            }
            
            _imageV = [[UIImageView alloc] init];
            _imageV.frame = CGRectMake(kScreen_Width/2-75, 230, 150, 150);
            _imageV.image = [UIImage imageNamed:@"zanwudizhi"];
            [self.view addSubview:_imageV];
            [self.tableView.mj_footer endRefreshing];
            _twoLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreen_Width/2-100, CGRectGetMaxY(_imageV.frame)+20, 200, 30)];
            _twoLabel.text = @"暂无地址，快来添加地址吧";
            _twoLabel.textColor = [UIColor grayColor];
            _twoLabel.font = kFont14;
            _twoLabel.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:_twoLabel];
            
            _daiNiFeiBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
            _daiNiFeiBtn.frame = CGRectMake(50, CGRectGetMaxY(_twoLabel.frame)+20, kScreen_Width - 100, 45);
            [_daiNiFeiBtn setBackgroundImage:[UIImage imageNamed:@"bg1"] forState:(UIControlStateNormal)];
            [_daiNiFeiBtn setTitle:@"添加地址" forState:(UIControlStateNormal)];
            _daiNiFeiBtn.layer.masksToBounds = YES;
            _daiNiFeiBtn.layer.cornerRadius = 3;
            [_daiNiFeiBtn addTarget:self action:@selector(addAddressBtnAction) forControlEvents:(UIControlEventTouchUpInside)];
            [self.view addSubview:_daiNiFeiBtn];
        }
        else {
            self.tableView.hidden = NO;
            [_daiNiFeiBtn removeFromSuperview];
            [_twoLabel removeFromSuperview];
            [_imageV removeFromSuperview];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
    
    
}
#pragma mark 添加地址按钮的点击事件

-(void)addAddressBtnAction{
    AddAddressInfoController *addressAdd = [[AddAddressInfoController alloc] init];
    addressAdd.pushType = @"0";
    [self.navigationController pushViewController:addressAdd animated:YES];
}

- (void)configureNaBar {
    //设置导航栏按钮的边距
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame= CGRectMake(0, 0, 60, 30);
    [rightBtn setImage:[UIImage imageNamed:@"all_fanhui2"] forState:(UIControlStateNormal)];
    [rightBtn addTarget:self action:@selector(handleBackAxtion) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *btn_left = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    UIBarButtonItem *negativeSpacerleft = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    /**
     width为负数时，相当于btn向右移动width数值个像素，由于按钮本身和  边界间距为5pix，所以width设为-5时，间距正好调整为0；width为正数 时，正好相反，相当于往左移动width数值个像素
     */
    negativeSpacerleft.width = -20;
    self.navigationItem.leftBarButtonItems = [NSArray arrayWithObjects:negativeSpacerleft, btn_left, nil];
    
    
    //设置导航栏按钮的边距
    _rightBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    _rightBtn2.frame= CGRectMake(0, 0, 60, 30);
    [_rightBtn2 setTitle:@"添加" forState:(UIControlStateNormal)];
    [_rightBtn2 addTarget:self action:@selector(addAddressBtnAction) forControlEvents:UIControlEventTouchUpInside];
    _rightBtn2.titleLabel.font = kFont16;
    [_rightBtn2 setTitleColor:[UIColor lightGrayColor] forState:(UIControlStateNormal)];
    UIBarButtonItem *btn_right = [[UIBarButtonItem alloc] initWithCustomView:_rightBtn2];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc]   initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace   target:nil action:nil];
    negativeSpacer.width = -20;
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:negativeSpacer, btn_right, nil];
    
}

- (void)handleBackAxtion {
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)addTableviewUI {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = BaseColor;
    [self.tableView registerNib:[UINib nibWithNibName:@"MyAddressTableViewCell" bundle:nil] forCellReuseIdentifier:identifier];
    [self.view addSubview:self.tableView];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 240;
    return self.tableView.rowHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MyAddressTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryNone;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    [cell.bianjiBtn addTarget:self action:@selector(handleEditAddress:) forControlEvents:(UIControlEventTouchUpInside)];
    [cell.morenAddressBtn addTarget:self action:@selector(setMorenAddress:) forControlEvents:UIControlEventTouchUpInside];
    [cell.deleteBtn addTarget:self action:@selector(deleteAdress:) forControlEvents:UIControlEventTouchUpInside];

    AddressListModel *modle = self.dataArray[indexPath.section];
    cell.nameTelLable.text = [NSString stringWithFormat:@"%@ %@",modle.full_name,modle.tel];
    cell.locationLable.text = modle.address;
    
    if (modle.is_default.integerValue == 1) {
        cell.morenAddressBtn.selected = YES;
    }else{
        cell.morenAddressBtn.selected = NO;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = BaseColor;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *footview = [[UIView alloc] init];
    footview.backgroundColor = BaseColor;
    
    return footview;
}



//删除默认地址按钮点击事件
-(void)deleteAdress:(UIButton *)sender{
    
    CancelDingDanView *cancelV = [[CancelDingDanView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    cancelV.delegate = self;
    cancelV.titleStr = @"小通提示";
    cancelV.centerStr = @"确认删除?";
    [self.view.window addSubview:cancelV];
    
    MyAddressTableViewCell *cell = (MyAddressTableViewCell *)[[sender superview] superview];
    deleteIndex = [_tableView indexPathForCell:cell];

}
-(void)cancelOrConfirm:(NSInteger)cancel{
    if (cancel == 0) {
        
    }else{
        
        NSDictionary *saveDic = [SaveDataMethord readLoginData];
        
        AddressListModel *model = self.dataArray [deleteIndex.section];
        
        NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"id":model.Id,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
        [HttpRequest postWithURLString:POST(Shop_DelDefaultAddress) parameters:parameDic success:^(id responseObject) {
            
            NSLog(@"%@",responseObject);
            NSDictionary *dataDic = [responseObject objectForKey:@"dasta"];
            
            if (dataDic.count) {
                NSString *codeStr = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"code"]];
                if (codeStr.integerValue == 0) {
                    
                    [self getData];
                }
                
                [MBProgressHUD showText:[NSString stringWithFormat:@"%@",[dataDic objectForKey:@"msg"]]];
                
            }
            
            [self getData];
            
        } failure:^(NSError *error) {
            
        }];
    }
}

//设置默认地址按钮点击事件
-(void)setMorenAddress:(UIButton *)sender{

    NSDictionary *saveDic = [SaveDataMethord readLoginData];
    
    MyAddressTableViewCell *cell = (MyAddressTableViewCell *)[[sender superview] superview];
    NSIndexPath *indepath = [_tableView indexPathForCell:cell];
    AddressListModel *model = self.dataArray [indepath.section];
    
    NSDictionary *parameDic = @{@"userid":saveDic[@"userid"],@"id":model.Id,@"actoken":[Md5Apiway getMD5data:saveDic[@"userid"]]};
    [HttpRequest postWithURLString:POST(Shop_EditDefaultAddress) parameters:parameDic success:^(id responseObject) {
        
        NSLog(@"%@",responseObject);
        NSDictionary *dataDic = [responseObject objectForKey:@"dasta"];
        
        if (dataDic.count) {
            NSString *codeStr = [NSString stringWithFormat:@"%@",[dataDic objectForKey:@"code"]];
            if (codeStr.integerValue == 0) {
                [self getData];
            }else{
                [MBProgressHUD showText:[NSString stringWithFormat:@"%@",[dataDic objectForKey:@"msg"]]];
            }
        }
        
        [self getData];
        
    } failure:^(NSError *error) {
        
    }];

}
//编辑地址按钮的点击事件
- (void)handleEditAddress:(UIButton *)sender {
    
    MyAddressTableViewCell *cell = (MyAddressTableViewCell*)[[sender superview] superview];
    NSIndexPath *indepath = [_tableView indexPathForCell:cell];
    AddressListModel *modle = self.dataArray[indepath.section];
    
    NSLog(@"点击的section ＝＝＝ %ld",indepath.section);
    AddAddressInfoController *vc = [[AddAddressInfoController alloc] init];
    vc.pushType = @"1";
    vc.modle = modle;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleDefault;

    [self getData];
}

//- (void)handleedit:(UIButton *)sender {
//    MyAddressTableViewCell *CELL = (MyAddressTableViewCell *)[[sender superview] superview];
//    NSIndexPath *inpath = [self.tableView indexPathForCell:CELL];
//    AddressListModel *model = self.dataArray [inpath.section];
//    
//    NSLog(@"--%ld",inpath.section);
//}

@end
